package com.huike.business.service.impl;


import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 商机跟进记录Service业务层处理
 *
 * @author wgl
 * @date 2021-04-28
 */
@Service
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {

    @Autowired
    private TbBusinessTrackRecordMapper tbBusinessTrackRecordMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private TbBusinessMapper tbBusinessMapper;

    private static final String DICT_TYPE = "communication_point";

    /**
     * 商机跟进记录表
     * @param id
     * @return
     */
    @Override
    public List<TbBusinessTrackRecord> list(Long id) {
        //根据id获取跟进记录
        List<TbBusinessTrackRecord> list = tbBusinessTrackRecordMapper.selectById(id);

        for (TbBusinessTrackRecord tbBusinessTrackRecord : list) {
            //获取跟进记录的keyItems
            String keyItems = tbBusinessTrackRecord.getKeyItems();
            String[] keys = keyItems.split(",");

            //根据keys查询字典表对应的值
            List<String> keysname = new ArrayList<>();
            for (String key : keys) {
                String label = sysDictDataMapper.selectDictLabel(DICT_TYPE,key);
                keysname.add(label);
            }
            tbBusinessTrackRecord.setKeys(keysname);
        }
        return list;
    }

    /**
     * 添加商机
     * @param businessTrackVo
     */
    @Override
    public void add(BusinessTrackVo businessTrackVo) {

        //插入商机记录表
        TbBusinessTrackRecord tbBusinessTrackRecord = new TbBusinessTrackRecord();
        BeanUtils.copyProperties(businessTrackVo,tbBusinessTrackRecord);
        tbBusinessTrackRecord.setCreateTime(new Date());
        String username = SecurityUtils.getUsername();
        tbBusinessTrackRecord.setCreateBy(username);
        tbBusinessTrackRecordMapper.add(tbBusinessTrackRecord);

        //跟新商机表
        TbBusiness tbBusiness = new TbBusiness();
        BeanUtils.copyProperties(businessTrackVo,tbBusiness);

        tbBusiness.setId(businessTrackVo.getBusinessId());
        tbBusiness.setStatus(businessTrackVo.getTrackStatus());

        tbBusinessMapper.updateTbBusiness(tbBusiness);
    }
}
